<?php


$LISTCONFIG_FILE = 'preconfigs.serialize';

$list_preconfig = array();
if (file_exists($LISTCONFIG_FILE)) {
	$list_preconfig = unserialize(file_get_contents($LISTCONFIG_FILE));
}

function getFilesNonHidden($path) {
	$lastchar = $path[strlen($path)-1];
	if ($lastchar != "/" && $lastchar != "\\") {
		$path .= "/";
	}
	
	$handler = opendir($path);
	
	$results = array();
	while ($d = readdir($handler)) {
		if ($d == "." || $d == ".." || $d[0] == ".") {
			continue;
		}
		$results[] = $d;
		if (is_dir($path.$d)) {
			$subfiles = getFilesNonHidden($path.$d);
			foreach ($subfiles as $f) {
				$results[] = $d."/".$f;
			}
		}
	}
	closedir($handler);
	
	return $results;
}

$msg = "";


$preconfig = array('name' => '', 'path' => '');

if (isset($_POST['preconfig']['save']) || isset($_POST['preconfig']['save_and_generate'])) {
	$preconfig = array(
		'name' => $_POST['preconfig']['name'],
		'path' => $_POST['preconfig']['path'],
		'files' => array()
	);
	if (isset($_POST['preconfig']['files'])) {
		$preconfig['files'] = $_POST['preconfig']['files'];
	}
	
	$founded = false;
	foreach ($list_preconfig as &$p) {
		if ($p['name'] == $preconfig['name']) {
			$p['path'] = $preconfig['path'];
			$p['files'] = $preconfig['files'];
			$founded = true;
			break;
		}
	}
	
	if (!$founded) {
		$list_preconfig[] = $preconfig;
	}
	file_put_contents($LISTCONFIG_FILE, serialize($list_preconfig));
}

$list_preconfig_sorted = array();
foreach ($list_preconfig as $i => $p) {
	$p['i'] = $i;
	$list_preconfig_sorted[$p['name']] = $p;
}
ksort($list_preconfig_sorted);
$selected_config = -1;

if (isset($_POST['preconfig']['load']) && isset($_POST['preconfig']['id'])) {
	$selected_config = $_POST['preconfig']['id'];
	$preconfig = $list_preconfig[$selected_config];

}

if (isset($_POST['preconfig']['save_and_generate']) && isset($preconfig['files'])) {
	$lines = array("CACHE MANIFEST", "", "#Last update: ".date('d/m/Y H:i:s'), "");
	$files = $preconfig['files'];
	$path = $preconfig['path'];
	if (substr($path,-1) != "/" && substr($path,-1) != "\\") {
		$path .= "/";
	}
	$totalsize = 0;
	foreach ($files as $f) {
		if (is_dir($path.$f)) {
			continue;
		} else {
			$totalsize += filesize($path.$f);
			$lines[] = $f;
		}
	}
	
	$suffixe = "o";
	if ($totalsize > 1024) {
		$totalsize = round($totalsize / 1024);
		$suffix = "ko";
	}
	
	file_put_contents($path."cache.manifest", implode("\n", $lines));
	$msg = "Le manifest '".$path."cache.manfifest' a été créé (taille webapp: $totalsize $suffix).";
}

$files = array();
if (!empty($preconfig['path'])) {
	$path = realpath($preconfig['path']);
	if (!empty($path)) {
		$files = getFilesNonHidden($path);
		sort($files);
	}
}

?>
<!doctype html>
<html lang="fr">
<head>
  <meta charset="utf-8">
  <title>Génération du cache manifest d'une webapp</title>
</head>
<body>
	<h3>Génération du cache manifest d'une webapp</h3>
	<? if (!empty($msg)):?>
	<strong><?= $msg ?></strong>
	<?endif; ?>
	<form method="POST">
	<fieldset>
		<legend>Charger une pré-configuration</legend>
	<div>
		<label for="preconfig_id">Pré-configuration</label>
		<select name="preconfig[id]" id="preconfig_id">
			<? foreach($list_preconfig_sorted as $i => $p):?>
				<? if ($selected_config == $i): ?>
				<option value="<?= $p['i'] ?>" selected="selected"><?= htmlentities($p['name'])?></option>
				<? else: ?>
				<option value="<?= $p['i'] ?>"><?= htmlentities($p['name'])?></option>
				<? endif; ?>
			<? endforeach;?>
			<? if (count($list_preconfig) == 0): ?>
			<option value="-1">Aucune défini</option>
			<? endif; ?>
		</select>
		<input type="submit" name="preconfig[load]" value="Charger"/>
		<input type="submit" name="preconfig[new]" value="Nouvelle"/>
	</div>
	</fieldset>
	<fieldset>
		<legend>Webapp</legend>
		<table style="border-style: none; border-spacing: 0px; border-collapse: collapse;">
			<tr>
				<td><label for="preconfig_name">Nom de la configuration</label></td>
				<td><input type="text" name="preconfig[name]" id="preconfig_name" value="<?= htmlentities($preconfig['name'])?>"/></td>
			</tr>
			<tr>
				<td><label for="preconfig_path">Chemin de la webapp</label></td>
				<td><input type="text" name="preconfig[path]" id="preconfig_path" value="<?= htmlentities($preconfig['path'])?>"/></td>
			</tr>
		</table>
		<? if (count($files)): ?>
		<input type="submit" value="Enregistrez la configuration et créer le manifest" name="preconfig[save_and_generate]" />
		<? else: ?>
		<input type="submit" value="Enregistrez la configuration et lister les fichiers" name="preconfig[save]" />
		<? endif; ?>
	</fieldset>
	<? if (count($files)): ?>
	<fieldset>
		<legend>Fichiers du manifest</legend>
		
		<br />
		<div>Sélectionner les fichiers à mettre dans le cache</div>
		<table style="border-style: none; border-spacing: 0px; border-collapse: collapse;">
			<tr>
				<td colspan="2">
					<input type="button" value="Tout sélectionner" id="btn-all-files-select"/>
					<input type="button" value="Tout désélectionner" id="btn-all-files-unselect"/>
				</td>
			</tr>
			<? foreach($files as $i => $f): ?>
			<tr>
				<? $checked = (count($preconfig['files']) == 0) ? true : (in_array($f, $preconfig['files']) ? true : false)?>
				<? if ($checked) $checked='checked="checked"'; ?>
				<td><input type="checkbox" name="preconfig[files][]" value="<?= htmlentities($f) ?>" <?= $checked?> id="files_<?= $i ?>" class="checkboxfile" /></td>
				<td><label for="files_<?= $i ?>"><?= htmlentities($f) ?></label></td>
			</tr>
			<? endforeach; ?>
		</table>
	</fieldset>
	<? endif; ?>
</body>
<script type="text/javascript">
var CreateCacheManifest = new (function() {
	
	var checkboxes = [];
	
	function changeRecursive() {
		var elem = this;
		var value = this.value;
		var state = this.checked;
		
		for (var i = 0; i < checkboxes.length; i++) {
			if (checkboxes[i].value.indexOf(this.value) == 0) {
				checkboxes[i].checked = state;
			}
		}
	}
	
	
	this.init = function() {
		var elems = document.getElementsByTagName("input");
		for (var i = 0; i < elems.length; i++) {
			if (elems[i].className == "checkboxfile") {
				elems[i].addEventListener("change", changeRecursive);
				checkboxes.push(elems[i]);
			}
		}
	};
	
	this.init();
	
});
</script>
</html>